layui.define(["table", "form", "upload", "admin"], function (exports) {
  var $ = layui.$,
    table = layui.table,
    form = layui.form,
    upload = layui.upload,
    admin = layui.admin;

  table.on("sort(LAY-user-manage)", function (obj) {
    table.reload("LAY-user-manage", {
      initSort: obj,
      where: {
        field: obj.field,
        order: obj.type,
      },
    });
  });
  //
  table.render({
    elem: "#LAY-admin-manage",
    toolbar: '#toolbaar',
    url: "/admin/admin/fetch_sub_anchors?admin_id=" + admin_id,
    sort: true,
    cols: [
      [
        { type: 'checkbox', fixed: 'left' },
        { field: "id", width: 150, title: "ID", fixed: "left" },
        {
          field: "nick_name",
          title: "昵称",
          width: 150,
          templet: function (d) {
            return decodeURI(d.nick_name);
          },
        },
        { field: "account", title: "账号", width: 150 },
        {
          field: "",
          title: "主播姓名",
          width: 100,
          templet: function (d) {
            if (d.anchor_auth) {
              return d.anchor_auth.real_name;
            }
            else {
              return "";
            }
          },
        },
        { field: "fans_count", title: "粉丝", width: 100 },
        { field: "tag", title: "标签", width: 150 },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-180",
    text: "对不起，加载出现异常！",
    even: true,
  });

  form.on('checkbox(sub_anchors)', function (data) {
    var req = data.value.split(",");
    layer.load();
    admin.req({
      url: "/admin/admin/update_sub_anchors",
      data: { id: req[0], admin_id: req[1], checked: data.elem.checked },
      success(res) {
        layer.closeAll();
        if (res.code == 0) {
          layer.msg(res.msg, { icon: 1 });
        }
        else {
          layer.msg(res.msg, { icon: 5 });
        }
      },
      complete(res) {
        layer.closeAll("loading");
      }

    });
  });

  table.on('toolbar(LAY-admin-manage)', function (obj) {
    var data = table.checkStatus(obj.config.id);
    var ids = new Array();
    for (let index = 0; index < data.data.length; index++) {
      ids.push(data.data[index].id)
    }

    if (ids.length == 0) {
      return
    }

    if (obj.event == 'sub_anchors_true') {
      layer.load();
      admin.req({
        url: "/admin/admin/update_sub_anchors",
        data: { ids: ids, admin_id: admin_id, checked: true },
        success(res) {
          layer.closeAll();
          if (res.code == 0) {
            layer.msg(res.msg, { icon: 1 });
          }
          else {
            layer.msg(res.msg, { icon: 5 });
          }
        },
        complete(res) {
          layer.closeAll("loading");
        }

      });
    }
    if (obj.event == 'sub_anchors_false') {
      layer.load();
      admin.req({
        url: "/admin/admin/update_sub_anchors",
        data: { ids: ids, admin_id: admin_id, checked: false },
        success(res) {
          layer.closeAll();
          if (res.code == 0) {
            layer.msg(res.msg, { icon: 1 });
          }
          else {
            layer.msg(res.msg, { icon: 5 });
          }
        },
        complete(res) {
          layer.closeAll("loading");
        }

      });
    }

  });

  table.render({
    elem: "#LAY-user-manage",
    url: "/admin/user/anchor_list",
    initSort: {
      field: "auth_time",
      type: "desc",
    },
    sort: true,
    cols: [
      [
        { field: "id", width: 100, title: "ID", fixed: "left" },
        {
          field: "nick_name",
          title: "昵称",
          minWidth: 100,
          templet: function (d) {
            return decodeURI(d.nick_name);
          },
        },
        { field: "account", title: "账号", width: 150 },
        {
          field: "",
          title: "主播姓名",
          width: 100,
          templet: function (d) {
            if (d.anchor_auth) {
              return d.anchor_auth.real_name;
            } else {
              return "";
            }
          },
        },
        { field: "fans_count", title: "粉丝", width: 100 },
        { field: "tag", title: "标签", width: 100 },
        {
          field: "",
          title: "联系QQ",
          width: 150,
          templet: function (d) {
            if (d.anchor_auth) {
              return d.anchor_auth.qq;
            } else {
              return "";
            }
          },
        },
        {
          field: "",
          title: "联系微信",
          width: 150,
          templet: function (d) {
            if (d.anchor_auth) {
              return d.anchor_auth.we_chat;
            } else {
              return "";
            }
          },
        },
        {
          field: "",
          title: "直播状态",
          width: 100,
          templet: function (d) {
            if (d.in_live) {
              return "<span class='layui-badge layui-bg-blue'>直播中</span>";
            } else {
              return "<span class='layui-badge layui-bg-cyan'>未开播</span>";
            }
          },
        },
        {
          field: "",
          title: "直播间公告",
          width: 150,
          templet: function (d) {
            if (d.anchor_live_notice) {
              return d.anchor_live_notice.content;
            } else {
              return "";
            }
          },
        },
        {
          field: "",
          title: "主播类型",
          width: 100,
          templet: function (d) {
            let type;
            if (d.anchor_type == 1) type = "普通主播";
            if (d.anchor_type == 2) type = "公司主播";
            if (d.anchor_type == 3) type = "测试主播";
            return type;
          },
        },

        {
          field: "",
          title: "竞猜权限",
          width: 100,
          templet: function (d) {
            if (d.is_guess_host) {
              return "<span class='layui-badge layui-bg' style='background-color: #1E9FFF;'>已开启</span>";
            }

            return "<span class='layui-badge' style='border: 1px solid #e6e6e6;background-color: #FBFBFB;color: #C9C9C9;'>未开启</span>";
          },
        },

        { field: "anchor_point", width: 100, title: "主播经验值" },

        {
          field: "auth_time",
          title: "认证时间",
          width: 170,
          sort: true,
          templet: function (d) {
            return d.auth_time ?? "";
          },
        },
        {
          field: "",
          title: "注册来源",
          width: 100,
          templet: function (d) {
            if (d.regist_type == 0) {
              return "后台";
            }
            if (d.regist_type == 1) {
              return "WEB";
            }
            if (d.regist_type == 2) {
              return "iOS";
            }
            if (d.regist_type == 3) {
              return "Android";
            } else {
              return "";
            }
          },
        },
        {
          field: "",
          title: "禁播时长",
          width: 120,
          templet: function (d) {
            if (d.anchor_banned) {
              return (
                "<span class='layui-badge layui-bg-red'>" +
                d.anchor_banned.ban_time_format +
                "</span>"
              );
            }
            return "";
          },
        },
        {
          field: "",
          title: "分成比例",
          width: 100,
          templet: function (d) {
            return d.sharing_ratio + "%";
          },
        },
        {
          field: "",
          title: "所属公会",
          width: 180,
          templet: function (d) {
            return d.guild ? d.guild.name : "平台";
          },
        },
        {
          field: "",
          title: "转化贵族总数",
          width: 150,
          align: "center",
          templet: function (d) {
            if (!d.recommend) {
              return "0";
            }
            if (!d.recommend.total_noble) {
              return "0";
            }

            return d.recommend.total_noble;
          },
        },
        {
          field: "",
          title: "转化新用户总数",
          width: 160,
          align: "center",
          templet: function (d) {
            if (!d.recommend) {
              return "0";
            }
            if (!d.recommend.total_recommend) {
              return "0";
            }

            return d.recommend.total_recommend;
          },
        },
        {
          title: "操作",
          width: 430,
          align: "center",
          fixed: "right",
          toolbar: "#table-userlist-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-180",
    text: "对不起，加载出现异常！",
    even: true,
  });


  table.on('toolbar(LAY-user-manage)', function (obj) {
    var data = table.checkStatus(obj.config.id);

    layer.confirm("确定要批量结束已勾选直播吗？", function (index) {
      if (obj.event == 'mult_end_live') {
        for (let index = 0; index < data.data.length; index++) {
          layer.load();
          admin.req({
            url: "/admin/live/stop_post",
            data: { liveid: data.data[index].liveid },
            success(res) {
              layer.closeAll();
              if (res.code == 0) {
                layer.msg(res.msg, { icon: 1 });
                table.reload("LAY-live-manage");
              }
              else {
                layer.msg(res.msg, { icon: 5 });
              }
            },
            complete(res) {
              layer.closeAll("loading");
            }

          });
        }
      }
    });
  });

  // 监听工具条
  table.on("tool(LAY-user-manage)", function (obj) {
    if (obj.event === "del") {
      layer.confirm("确定封禁/解封用户？", function (index) {
        var status = obj.data.status == 0 ? 1 : 0;
        admin.req({
          url: "/admin/user/del_post",
          data: { id: obj.data.id, status: status },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-manage");
              layer.msg(res.msg, { icon: 1 });
            }
            else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    }
    else if (obj.event === "edit") {
      var index = layer.open({
        type: 2,
        title: "编辑用户",
        content: "/admin/user/edit?id=" + obj.data.id,
        maxmin: true,
        area: ["800px", "510px"],
      });
      layer.full(index);
    }
    else if (obj.event === "fans_edit") {
      layer.open({
        type: 2,
        title: "设置粉丝数量",
        content: "/admin/user/fans_edit?id=" + obj.data.id,
        maxmin: true,
        area: ["480px", "330px"],
      });
    }
    else if (obj.event == "setAdmin") {
      layer.confirm("确定将改用户设为房间管理？", function (index) {
        admin.req({
          url: "/admin/user/setAdmin",
          data: { id: obj.data.id },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-manage");
              layer.msg(res.msg, { icon: 1 });
            }
            else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    }
    else if (obj.event == "delAdmin") {
      layer.msg("请到房间管理员列表页面取消管理身份", { icon: 5 });
    }
    else if (obj.event == "bannerd") {
      layer.open({
        type: 2,
        title: "编辑用户",
        content: "/admin/user/anchor_set_banned?id=" + obj.data.id,
        maxmin: true,
        area: ["500px", "350px"],
      });
    }
    else if (obj.event == "unbannerd") {
      layer.confirm("确定解除禁播?", function () {
        admin.req({
          url: "/admin/user/anchor_unbanned",
          data: { id: obj.data.id },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-manage");
              layer.msg(res.msg, { icon: 1 });
            }
            else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    }
    else if (obj.event == "editLiveRoomNotice") {
      var notice_content = obj.data.anchor_live_notice
        ? obj.data.anchor_live_notice.content
        : "兄弟姐妹们关注点起来不迷路";
      layer.prompt(
        {
          formType: 2,
          value: notice_content,
          title: "修改直播间公告",
          area: ["400px", "300px"], // 自定义文本域宽高
        },
        function (value, index, elem) {
          admin.req({
            url: "/admin/live/anchor_room_notice_edit",
            data: { anchorid: obj.data.id, content: value },
            success: function (res) {
              if (res.code == 0) {
                layer.close(index);
                layer.msg(res.msg, { icon: 1 });
                table.reload("LAY-user-manage");
              }
            },
          });
        });
    }
    else if (obj.event == "advertising") {
      layer.open({
        type: 2,
        title: "编辑屏幕广告",
        content: "/admin/user/advertising?id=" + obj.data.id,
        maxmin: true,
        area: ["500px", "620px"],
      });
    }
  });

  form.on("submit(user-add)", function (obj) {
    var data = obj.field;
    layer.load();
    // 提交
    admin.req({
      url: "/admin/user/add_post",
      data: data,
      success: function (res) {
        if (res.code == 0) {
          layer.msg(res.msg, { icon: 1 });
          setTimeout(function () {
            window.location.reload();
          }, 1200);
        }
        else {
          setTimeout(function () {
            window.location.reload();
          }, 2200);
        }
      },
      done: function () {
        layer.closeAll("loading");
      },
    });
    return false;
  });

  // 上传头像
  var avatarSrc = $("#LAY_avatarSrc");
  upload.render({
    url: "/admin/index/noOperation",
    elem: "#LAY_avatarUpload",
    auto: true,
    choose: function (obj) {
      layer.load();
      var choosefile;
      obj.preview(function (index, file, result) {
        choosefile = file;
      });
      admin.req({
        url: "/admin/user/signForCos",
        success: function (res) {
          if (res.code == 0) {
            var cos = new COS({
              getAuthorization: function (options, callback) {
                var credentials = res.data.credentials;
                callback({
                  TmpSecretId: credentials.tmpSecretId,
                  TmpSecretKey: credentials.tmpSecretKey,
                  XCosSecurityToken: credentials.sessionToken,
                  ExpiredTime: res.data.expiredTime,
                });
              },
              Domain:res.data.imgDomain,
            });
            cos.putObject(
              {
                Bucket: res.data.bucket,
                Region: res.data.region,
                Key: "images/" + res.data.filename + choosefile.name,
                Body: choosefile,
              },
              function (err, data) {
                layer.closeAll("loading");
                if (err) {
                  layer.msg("上传失败", { icon: 5 });
                }
                else {
                  if (data.statusCode == 200) {
                    avatarSrc.val("https://" + data.Location);
                  }
                  else {
                    layer.msg("图片上传失败", { icon: 5 });
                  }
                }
              });
          }
          else {
            layer.closeAll("loading");
            layer.msg(res.msg, { icon: 5 });
          }
        },
        error: function () {
          layer.closeAll("loading");
        },
      });
    },
  });

  // 查看头像
  admin.events.avartatPreview = function (othis) {
    var src = avatarSrc.val();
    if (src) {
      layer.photos({
        photos: {
          title: "查看头像", // 相册标题
          data: [
            {
              src: src, // 原图地址
            },
          ],
        },
        shade: 0.01,
        closeBtn: 1,
        anim: 5,
      });
    }
  };

  // 上传封面图
  var coverImgSrc = $("#LAY_coverImgSrc");
  upload.render({
    url: "/admin/index/noOperation",
    elem: "#LAY_coverImgUpload",
    auto: true,
    choose: function (obj) {
      layer.load();
      var choosefile;
      obj.preview(function (index, file, result) {
        choosefile = file;
      });
      admin.req({
        url: "/admin/user/signForCos",
        success: function (res) {
          if (res.code == 0) {
            var cos = new COS({
              getAuthorization: function (options, callback) {
                var credentials = res.data.credentials;
                callback({
                  TmpSecretId: credentials.tmpSecretId,
                  TmpSecretKey: credentials.tmpSecretKey,
                  XCosSecurityToken: credentials.sessionToken,
                  ExpiredTime: res.data.expiredTime,
                });
              },
            });
            cos.putObject(
              {
                Bucket: res.data.bucket,
                Region: res.data.region,
                Key: "images/" + res.data.filename + choosefile.name,
                Body: choosefile,
              },
              function (err, data) {
                layer.closeAll("loading");
                if (err) {
                  layer.msg("上传失败", { icon: 5 });
                }
                else {
                  if (data.statusCode == 200) {
                    coverImgSrc.val("https://" + data.Location);
                  }
                  else {
                    layer.msg("图片上传失败", { icon: 5 });
                  }
                }
              });
          }
          else {
            layer.closeAll("loading");
            layer.msg(res.msg, { icon: 5 });
          }
        },
      });
    },
  });

  // 查看封面图
  admin.events.coverImgPreview = function (othis) {
    var src = coverImgSrc.val();
    if (src) {
      layer.photos({
        photos: {
          title: "查看头像", // 相册标题
          data: [
            {
              src: src, // 原图地址
            },
          ],
        },
        shade: 0.01,
        closeBtn: 1,
        anim: 5,
      });
    }
  };

  // 查看照片
  admin.events.photosPreview = function (othis) {
    let urls = othis.attr("value");
    let urlarr = new Array();
    $.each(urls.split(","), function (i, val) {
      urlarr.push({ src: val });
    });
    layer.photos({
      photos: {
        title: "查看照片", // 相册标题
        data: urlarr,
      },
      shade: 0.01,
      closeBtn: 1,
      anim: 5,
    });
  };

  ///////////////////////////////////////////////  report ////////////////////////////////////////////////

  table.render({
    elem: "#LAY-user-report-manage",
    url: "/admin/user/getReportList",
    cols: [
      [
        { field: "id", width: 100, title: "ID", sort: true, fixed: "left" },
        {
          field: "",
          title: "举报用户",
          width: 200,
          templet: function (d) {
            return d.user.nick_name + "(" + d.uid + ")";
          },
        },
        {
          field: "",
          title: "被举报用户",
          width: 200,
          templet: function (d) {
            return d.anchor.nick_name + "(" + d.anchor.id + ")";
          },
        },
        { field: "title", title: "举报理由", width: 200 },
        { field: "content", title: "举报内容", minWidth: 200 },
        {
          field: "",
          title: "图片",
          width: 80,
          templet: function (d) {
            if (d.img_urls && d.img_urls.length > 0) {
              let images = d.img_urls.split(",");
              return (
                '<img style="display: inline-block; width: auto; height: 100%;" src= "' +
                images[0] +
                '" layadmin-event="photosPreview" value="' +
                d.img_urls +
                '">');
            }
            return "";
          },
        },
        {
          title: "操作",
          width: 150,
          align: "center",
          fixed: "right",
          toolbar: "#table-userlist-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-140",
    text: "对不起，加载出现异常！",
    even: true,
  });

  // 监听工具条
  table.on("tool(LAY-user-report-manage)", function (obj) {
    console.log(obj);
    if (obj.event === "view") {
      var index = layer.open({
        type: 2,
        title: "短视频",
        content: "/admin/user/edit?id=" + obj.data.userid,
        maxmin: true,
        area: ["600px", "550px"],
      });
      layer.full(index);
    }
  });

  ///////////////////////////////////////////////  room-admin ////////////////////////////////////////////////

  table.render({
    elem: "#LAY-user-room-admin",
    url: "/admin/user/getRoomAminList",
    cols: [
      [
        { field: "id", title: "ID", sort: true, fixed: "left" },
        { field: "mgrid", title: "管理员ID" },
        {
          field: "anchorid",
          title: "主播ID",
          templet: function (d) {
            if (d.anchorid == 0) {
              return "<font color='red'>所有主播房间</font>";
            }
            else {
              return d.anchorid;
            }
          },
        },
        { field: "create_time", title: "创建时间" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          toolbar: "#table-useradmin-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-140",
    text: "对不起，加载出现异常！",
    even: true,
  });

  // 监听工具条
  table.on("tool(LAY-user-room-admin)", function (obj) {
    if (obj.event === "setAdmin") {
      layer.confirm("确定取消该用户？", function (index) {
        admin.req({
          url: "/admin/user/setAdmin",
          data: { id: obj.data.mgrid },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-room-admin");
              layer.msg(res.msg, { icon: 1 });
            }
            else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    }
  });

  ///////////////////////////////////////////////  room-banned ////////////////////////////////////////////////
  table.render({
    elem: "#LAY-user-room-banned",
    url: "/admin/user/getBannedList",
    cols: [
      [
        { field: "id", title: "ID", sort: true, fixed: "left" },
        { field: "uid", title: "用户ID" },
        {
          field: "mgrid",
          title: "管理员ID",
          templet: function (d) {
            if (d.anchorid == 0) {
              return "后台管理员";
            }
            else {
              return d.mgrid;
            }
          },
        },
        {
          field: "anchorid",
          title: "主播ID",
          templet: function (d) {
            if (d.anchorid == 0) {
              return "<font color='red'>所有主播房间</font>";
            }
            else {
              return d.anchorid;
            }
          },
        },
        { field: "create_time", title: "创建时间" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          toolbar: "#table-userbanned-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-140",
    text: "对不起，加载出现异常！",
    even: true,
  });

  exports("anchor", {});
});
